package com.hmall.order.interceptors;

import com.hmall.order.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 请求拦截器
 *
 * @Author Eeyore
 * @Date 2022/8/12 17:35
 * @Description: 请求拦截器
 */
@Slf4j
public class AuthorizationHandlerInterceptor implements HandlerInterceptor {

    /**
     * 目标Handler执行之前
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断authorization请求头是否为空
        String userId = request.getHeader("authorization");
        log.warn("-------当前userId为{}", userId);
        if (StringUtils.isNotBlank(userId)) {
            //非空，绑定到Theradlocal上，放行
            UserHolder.setUser(Long.valueOf(userId));
            return true;
        }

        //为空，未登录,未认证【401】
        response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        response.setContentType("application/json:charset=UTF-8");
        response.getWriter().write("{\"message\"},\"非法用户，禁止访问\"}");
        return false;

    }


    /**
     * 渲染视图之后
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();

    }
}